package cn.wonderland.org.service.impl;

import cn.wonderland.base.enm.LogStateEnum;
import cn.wonderland.base.enm.ShopStateEnum;
import cn.wonderland.base.util.BaiduAuditUtils;
import cn.wonderland.base.util.BussinessException;
import cn.wonderland.base.util.LoginContext;
import cn.wonderland.base.util.MailUtils;
import cn.wonderland.org.domain.Employee;
import cn.wonderland.org.domain.Shop;
import cn.wonderland.org.domain.ShopAuditLog;
import cn.wonderland.org.dto.EmployeeDto;
import cn.wonderland.org.dto.ShopAuditDto;
import cn.wonderland.org.dto.ShopDto;
import cn.wonderland.org.mapper.EmployeeMapper;
import cn.wonderland.org.mapper.ShopAuditLogMapper;
import cn.wonderland.org.mapper.ShopMapper;
import cn.wonderland.org.service.IShopService;
import cn.wonderland.base.service.impl.BaseServiceImpl;
import cn.wonderland.org.vo.ShopVo;
import cn.wonderland.system.domain.Role;
import cn.wonderland.system.mapper.RoleMapper;
import cn.wonderland.user.domain.Logininfo;
import cn.wonderland.user.mapper.LogininfoMapper;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Collections;
import java.util.Date;
import java.util.List;
import java.util.Optional;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author wonderland
 * @since 2022-12-26
 */
@Service
public class ShopServiceImpl extends BaseServiceImpl<Shop> implements IShopService {
    @Autowired
    private ShopMapper shopMapper;
    @Autowired
    private EmployeeMapper employeeMapper;
    @Autowired
    private ShopAuditLogMapper logMapper;
    @Autowired
    private LogininfoMapper logininfoMapper;
    @Autowired
    private RoleMapper roleMapper;

    @Override
    public void settlement(ShopDto dto) {
        // 1.参数校验  通过注解校验

        // 校验参数
        verify(dto);
        // 保存数据
        save(dto);

    }

    // 审核通过
    @Override
    public void auditPass(ShopAuditDto dto) {
        // 1.校验参数
        // 2.修改状态
        Shop shop = new Shop();
        shop.setId(dto.getShopId());
        shop.setState(ShopStateEnum.AUDIT_PASS.getCode());
        shopMapper.update(shop);
        // 3.保存日志
        ShopAuditLog log = new ShopAuditLog();
        log.setShopId(dto.getShopId());
        log.setNote(dto.getNote());
        log.setAuditTime(new Date());
        log.setState(shop.getState());
        // todo 还没学登录 先留着 写死一个参数
        log.setAuditId(LoginContext.getLogininfo().getId());
        logMapper.add(log);
        // 4.发送邮件 告知用户审核成功，点击激活链接
        MailUtils.sendMail("1562017408@qq.com","" +
                "<h1>尊敬的客户，您的开店申请已经通过审核，请点击下方链接激活您的店铺：</h1>" +
                "http://localhost:8080/shop/activity/" + dto.getShopId(),"审核通过请激活！");
    }

    // 审核不通过
    @Override
    public void auditReject(ShopAuditDto dto) {
        // 1.校验参数
        // 2.修改状态
        Shop shop = new Shop();
        shop.setId(dto.getShopId());
        shop.setState(ShopStateEnum.AUDIT_REJECT.getCode());
        shopMapper.update(shop);
        // 3.保存日志
        ShopAuditLog log = new ShopAuditLog();
        log.setShopId(dto.getShopId());
        log.setNote(dto.getNote());
        log.setAuditTime(new Date());
        log.setState(shop.getState());
        // todo 还没学登录 先留着 写死一个参数
        log.setAuditId(LoginContext.getLogininfo().getId());
        logMapper.add(log);
        // 4.发送邮件 告知用户审核成功，点击激活链接
        MailUtils.sendMail("1562017408@qq.com","" +
                "<h1>尊敬的客户，您的开店申请没用通过审核，请点击下方链接重新填写相关信息：</h1>" +
                "http://localhost:8081/#/registerAgain?shopId="+dto.getShopId(),"审核未通过，请重新填写！");

    }

    // 再次入驻
    @Override
    public void settlementAgain(ShopVo shopVo) {
        Shop shop = new Shop();
        BeanUtils.copyProperties(shopVo,shop);
        shop.setState(ShopStateEnum.AUDIT.getCode());
        shopMapper.update(shop);
    }

    // 导入时 批量写入
    @Override
    public void batchSave(List<Shop> shops) {
        shopMapper.batchSave(shops);

    }

    // 激活
    @Override
    public void activity(Long id) {
        Shop shop = new Shop();
        shop.setId(id);
        shop.setState(ShopStateEnum.ACTIVITY.getCode());
        shopMapper.update(shop);

    }



    private void save(ShopDto dto) {
        // 6.添加信息
        // 添加shop
        Shop shop = dto.getShop();
        super.add(shop);
        // 添加emp
        Employee employee = new Employee();
        EmployeeDto admin = dto.getAdmin();
        BeanUtils.copyProperties(admin,employee);
        employee.setState(1);
        employee.setAge(0);
        employee.setShopId(shop.getId());
        // 同步logininfo表
        Logininfo logininfo = new Logininfo();
        BeanUtils.copyProperties(employee,logininfo);
        logininfo.setType(0);
        logininfo.setDisable(1);
        logininfoMapper.add(logininfo);
        // 更新emp表的logininfoId
        employee.setLogininfoId(logininfo.getId());
        employeeMapper.add(employee);
        // 默认给当前人添加店长角色 如果确定店长的id可以直接写死
        List<Role> roleList = roleMapper.findAll();
        Optional<Role> any = roleList.stream().filter(role -> "dz001".equals(role.getSn())).findAny();
        any.ifPresent(role->{
            roleMapper.addMiddle(employee.getId(), Collections.singletonList(role.getId()));
        });
        // 修改shop adminId
        Shop updateShop = new Shop();
        updateShop.setId(shop.getId());
        updateShop.setAdminId(employee.getId());
        super.update(updateShop);
    }

    private void verify(ShopDto dto) {
        // 2.两次密码是否一致
        if(!dto.getAdmin().getPassword().equals(dto.getAdmin().getComfirmPassword())){
            throw new BussinessException("两次密码不一致！");
        }

        // 3. 百度ai审核
        if(!BaiduAuditUtils.TextCensor(dto.getName())){
            throw new BussinessException("店铺名称不合规！");
        }
        if(!BaiduAuditUtils.ImgCensor(dto.getLogo())){
            throw new BussinessException("店铺logo不合规！");
        }

        // 4.店铺是否存在 通过名字校验
        String shopName = dto.getName();
        // 根据店铺名称去查询数据库，如果有表示重复，则抛出异常
        Shop shopDb = shopMapper.findByName(shopName);
        if(shopDb != null){
            throw new BussinessException("店铺已存在，请直接登录！");
        }

        // 5.管理员是否重复
        // 5.1 根据管理员name查询管理员是否存在
        String empName = dto.getAdmin().getUsername();
        // 5.2 管理员如果存在，查询是否有
        Employee employee = employeeMapper.findByName(empName);
        if(employee != null && null != employee.getShopId()){ // 不为空表示有这个员工，但是还要查该员工有没有管理店铺
            // 在emp表中的管理员id(adminId)表示该员工是管理员，如果我们查询的员工id与管理员id对应。
            // 证明该员工已经管理了店铺
            shopDb = shopMapper.findByAdminId(employee.getId());
            if (shopDb != null) {
                throw new BussinessException("管理员重复，请重新选择员工！");
            }

        }
    }
}
